import { TooltipProps } from 'antd';
import React, { HTMLAttributes, useEffect, useRef, useState } from 'react';
import type { CSSProperties } from 'styled-components';
import styled from 'styled-components';
import { CustomTooltip } from './CustomTooltip';

const CellWrap = styled.div`
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-all;
  white-space: normal;
  text-overflow: ellipsis;
`;

interface Props<T = any> extends HTMLAttributes<T> {
  /** 输入文本、数字 */ text: React.ReactNode;
  /** 行数，默认2行，溢出省略号 */ lines?: number | string;
  /** 个性化样式 */ style?: CSSProperties;
  /** 点击事件 */ onClick?: () => void;
  tooltipProps?: TooltipProps;
}

export const Ellipsis: React.FC<Props> = (props) => {
  const { text = '', lines = 2, style = {}, tooltipProps, onClick } = props;

  const ref = useRef(null);
  const elemId = `ellipsis-${+new Date()}`;
  const [isEllipsis, setIsEllipsis] = useState(false);

  useEffect(() => {
    if (ref?.current) {
      const elem = document.getElementById(elemId) ?? null;
      if (elem && elem.scrollHeight > elem.offsetHeight) {
        setIsEllipsis(true);
      }
    }
  }, [elemId]);

  return (
    <CellWrap
      id={elemId}
      ref={ref}
      onClick={onClick}
      style={{
        WebkitLineClamp: lines,
      }}>
      <CustomTooltip {...tooltipProps} title={!isEllipsis ? null : text}>
        <span style={style}>{text}</span>
      </CustomTooltip>
    </CellWrap>
  );
};
